package com.cs.framework.jdbc.hibernate3.session.module;

import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

import com.cs.framework.common.util.IOUtils;
import com.cs.framework.core.context.Module;
import com.cs.framework.core.util.CoreConstant;
import com.cs.framework.jdbc.common.util.DBConstant;
import com.cs.framework.jdbc.hibernate3.exception.HibernateExceptionHelper;
import com.cs.framework.jdbc.hibernate3.session.AbstractHibernateSessionFactory;

/**
 * 支持Hibernate注解的SessionFactory
 * 
 * @author hedongzhou
 * 
 */
public class ModuleSessionFactory extends AbstractHibernateSessionFactory implements ApplicationContextAware {

	/**
	 * 模块上下文
	 */
	protected Module module;

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		module = (Module) applicationContext;
	}

	public ConfigurableApplicationContext getApplicationContext() {
		return (ConfigurableApplicationContext) module;
	}

	/**
	 * 构建工厂
	 */
	public void buildSessionFactory() throws Exception {
		// 创建SessionFactory
		sessinFactoryBean = new AnnotationSessionFactoryBean();
		// 获取数据源
		sessinFactoryBean.setDataSource(dataSource);
		// 扫描package底下的注解类
		sessinFactoryBean.setPackagesToScan(module.getPackagePath() + DBConstant.MODULE_DTO_PATHPATTERN);

		// 映射文件路径
		Resource[] mappingRes = IOUtils.loadResource(CoreConstant.CLASSPATH_PATTERN + module.getPackageUrl()
				+ DBConstant.MODULE_HIBERNATE_CUSTOM_CONF);
		if (mappingRes != null && mappingRes.length > 0) {
			// 添加映射文件
			sessinFactoryBean.setMappingLocations(mappingRes);
		}

		// 判断是否指定了属性配置文件路径
		if (propertiesPath == null) {
			HibernateExceptionHelper.throwJdbcException("H001");
		} else {
			Resource res = IOUtils.loadOneResource(propertiesPath);

			// 判断是否存在属性配置文件
			if (res == null) {
				HibernateExceptionHelper.throwJdbcException("H002");
			} else {
				// 获取属性配置信息
				hibernateProperties = new Properties();
				hibernateProperties.load(res.getInputStream());

				// 设置hibernate属性
				sessinFactoryBean.setHibernateProperties(hibernateProperties);
			}
		}

		sessinFactoryBean.afterPropertiesSet();
	}

}
